class Category < ActiveRecord::Base
	
	has_many :posts, :dependent => :destroy
	has_many :categories, :foreign_key => "parent_id", :dependent => :destroy
  belongs_to :user_level_rule
	belongs_to :category

  validates_presence_of :name
	
	def self.get_category_posts( id )
		posts = Post.find(:all, :conditions => [ "parent_id is NULL AND category_id = ?", id ])
		posts = Post.sort_posts( posts )
		return posts
	end

  def self.post_level_id( id )
    c = Category.find_by_id(id)
    return (c.user_level_rule.post_level_id).to_i
  end

  def self.reply_level_id( id )
    p = Post.find_by_id( id )
    return (p.category.user_level_rule.reply_level_id).to_i
  end

  def self.view_level_id( id )
    c = Category.find_by_id( id )
    if !c.nil?
      return (c.user_level_rule.view_level_id).to_i
    else
      return UserLevel.find_by_name("Public").id
    end

  end

	def children
		return Category.find_all_by_parent_id(self.id)
	end

end
